/*
 * axios 二次封装
 * @author Leriy
*/
import axios from 'axios';
import config from '@/config/index.js';
import { getCookie, clearAllCookie } from '@/utils/storage.js'
import router from '@/router/index.js';

const service = axios.create({
    baseURL: config.baseApi,
    timeout: 8000
})

// 请求拦截
service.interceptors.request.use((req) => {
    const { token } = getCookie('userInfo') ? JSON.parse(getCookie('userInfo')) : ''
    if (!token && router.currentRoute.value.name != 'Login') {
        clearAllCookie()
        ElMessage.error('身份已过期,请重新登录!')
        setTimeout(() => { router.push('/login') }, 1500)
    }
    else req.headers['Authorization'] = 'Bearer ' + token

    return req
})

// 响应拦截
service.interceptors.response.use(
    (res) => {
        // 需要处理code为 201、202等情况
        const { code, data, msg } = res.data
        if (code == 200) return Promise.resolve(data)
        else {
            // 50001 Token失效重新登录
            if (code == 50001) {
                clearAllCookie()
                setTimeout(() => { router.push('/login') }, 1500)
            }
            ElMessage.error(msg)
            return Promise.reject(res.data)
        }
    },
    (error) => {
        ElMessage.error(msg)
    }
)

export default service;